/*
 * $RCSfile: TableAction.java,v $$
 * $Revision: 1.1 $
 * $Date: 2013-03-19 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.webcat.action;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skin.j2ee.action.BaseAction;
import com.skin.j2ee.annotation.UrlPattern;
import com.skin.j2ee.util.JsonUtil;
import com.skin.webcat.database.sql.SqlPlus;
import com.skin.webcat.database.sql.SqlResult;
import com.skin.webcat.util.Jdbc;
import com.skin.webcat.util.Webcat;

/**
 * <p>Title: TableAction</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class SqlPlusAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(SqlPlusAction.class);

    /**
     * @throws ServletException
     * @throws IOException
     */
    @UrlPattern("/webcat/sqlplus.html")
    public void query() throws ServletException, IOException {
        String name = this.getTrimString("name");
        String database = this.getTrimString("database");
        String tableName = this.getTrimString("tableName");
        this.setAttribute("name", name);
        this.setAttribute("database", database);
        this.setAttribute("tableName", tableName);
        this.forward("/template/webcat/sqlplus.jsp");
    }

    /**
     * @throws ServletException
     * @throws IOException
     */
    @UrlPattern("/webcat/sqlplus/execute.html")
    public void execute() throws ServletException, IOException {
        Connection connection = null;
        String name = this.getTrimString("name", "");
        String database = this.getTrimString("database");
        String sql = this.getTrimString("sql");

        try {
            connection = Webcat.getConnection(name, database);
            connection.setAutoCommit(false);
            SqlResult sqlResult = SqlPlus.execute(connection, sql);
            JsonUtil.callback(this.request, this.response, sqlResult);
        }
        catch(Exception e) {
            logger.error(e.getMessage(), e);
            JsonUtil.error(this.request, this.response, e.getMessage());
        }
        finally {
            Jdbc.close(connection);
        }
    }
}
